package com.prs.crm.action.purchase;

import java.util.Collection;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.Constrains;
import com.prs.crm.domain.fs.BankAccount;
import com.prs.crm.domain.fs.Detail;
import com.prs.crm.domain.fs.PayWay;
import com.prs.crm.domain.purchase.PaymentDetails;
import com.prs.crm.domain.purchase.PaymentGather;
import com.prs.crm.domain.purchase.PaymentOrder;
import com.prs.crm.domain.purchase.PurchaseOrder;
import com.prs.crm.domain.purchase.Votecounting;
import com.prs.crm.domain.sale.InvoiceType;
import com.prs.crm.domain.store.StoreRoom;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeInvoice;
import com.prs.crm.service.fs.BankAccountService;
import com.prs.crm.service.fs.DetailService;
import com.prs.crm.service.fs.PayWayService;
import com.prs.crm.service.purchase.PaymentDetailService;
import com.prs.crm.service.purchase.PaymentGatherService;
import com.prs.crm.service.purchase.PaymentOrderService;
import com.prs.crm.service.purchase.PurchaseOrderService;
import com.prs.crm.service.purchase.VotecountingService;
import com.prs.crm.service.sale.InvoiceTypeService;
import com.prs.crm.service.stock.StoreRoomService;
import com.prs.crm.service.sys.CodeInvoiceService;
import com.prs.crm.service.sys.CodeService;

/**
 * @author 兰小刚
 * @version 创建时间：2010-7-15 下午02:45:10 类说明
 */
public class PayMentAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private String Encode;

	private CodeInvoice codeInvoice;

	private CodeInvoiceService codeInvoiceService;
	private Code code;

	private CodeService codeService;

	private Collection<CodeInvoice> codelist;

	private PurchaseOrder purchaseOrder;

	private PaymentOrder paymentOrder;

	private PayWay payWay;
	private String payMony;

	private Votecounting votecounting;

	private BankAccount bankAccount;

	private PaymentDetails paymentDetail;

	private PaymentGather paymentGather;

	private PurchaseOrderService purchaseOrderService;

	private PayWayService payWayService;

	private PaymentDetailService paymentDetailService;

	private VotecountingService votecountingService;

	@Autowired
	private StoreRoomService storeRoomService;

	private DetailService detailService;

	private BankAccountService bankAccountService;

	private PaymentOrderService paymentOrderService;

	private PaymentGatherService paymentGatherService;

	private InvoiceTypeService invoiceTypeService;

	private List<PayWay> payWaylist;

	private Collection<BankAccount> bankAccounts;

	private List<StoreRoom> storerooms;

	private List<Votecounting> votecountings;

	private List<InvoiceType> InvoiceTypes;

	private PaginationSupport pagination;

	@Clew(results = { "success", "none" })
	@Action(value = "savePayMentDetail", results = {
			@Result(name = "success", type = "redirect", location = "editNotNullPayPlan?paymentOrder=${paymentOrder.getId()}"),
			@Result(name = "error", type = "chain", location = "editAddPaymentPlan"),
			@Result(name = "none", type = "redirect", location = "editNotNullPayPlan?paymentOrder=${paymentOrder.getId()}") })
	public String savePayMentDetail() {

		if ("n".equals(Encode)) {
			int EncodeRplice = this.getCodeService().getBackRpliceAll("手动编码",
					"采购票据单", paymentDetail.getBillCode());
			if (EncodeRplice != 0) {
				this.addActionError("编码重复!请重新输入");
				return ERROR;
			}
		}
		/**
		 * 付款单修改
		 */
		if ("x".equals(Encode) || "".equals(Encode)) {
			this.addActionError("请选择编码类型");
			return ERROR;
		}
		if (payMony == null || payMony.equals("")) {
			this.addActionError("付款金额不能为空");
			return ERROR;
		}
		try {
			Double.parseDouble(payMony);
		} catch (Exception e) {
			this.addActionError("只能位数字");
			return ERROR;
		}
		if (paymentDetail.getPayDate() == null) {
			this.addActionError("计划付款日期不能为空");
			return ERROR;
		}
		if (paymentDetail.getBillDate() == null) {
			this.addActionError("开票日期不能为空");
			return ERROR;
		}
		if (paymentDetail.getBilltype() == null) {
			this.addActionError("票据类型不能为空");
			return ERROR;
		}
		if (paymentDetail.getBillCode() == null
				|| paymentDetail.getBillCode().equals("")) {
			this.addActionError("票据单号不能为空");
			return ERROR;
		}
		paymentDetail.setPayMony(Double.parseDouble(payMony));
		PaymentOrder PaymentOrderObject = this.getPaymentOrderService()
				.getPaymentOrder(paymentOrder.getId());
		if (PaymentOrderObject.getArealymony() == null
				|| PaymentOrderObject.getArealymony() == 0) {
			PaymentOrderObject.setArealymony(paymentDetail.getPayMony());
		} else {
			PaymentOrderObject.setArealymony(PaymentOrderObject.getArealymony()
					+ paymentDetail.getPayMony());
		}
		if (PaymentOrderObject.getArealymony()
				- PaymentOrderObject.getPayMony() == 0) {
			PaymentOrderObject.setPatState(2);
		} else {
			PaymentOrderObject.setPatState(2);
		}
		PaymentGather PaymentGatherObject = this.getPaymentGatherService()
				.getPaymentGather(paymentOrder);
		if (PaymentGatherObject == null) {
			PaymentGather PaymentGatherOB = new PaymentGather();
			PaymentGatherOB.setPaymentOrder(PaymentOrderObject);
			PaymentGatherOB.setPayRealityMony(0.0);
			PaymentGatherOB.setBillMony(0.0);
			PaymentGatherOB.setPurchaseMony(paymentDetail.getPayMony());
			PaymentGatherOB.setPayPlanMony(paymentDetail.getPayMony());

			PaymentGatherOB.setPayState(2);

			PaymentGatherOB.setArelityState(2);
			this.getPaymentGatherService().save(PaymentGatherOB);
			paymentDetail.setPaymentGather(PaymentGatherOB);

			PaymentOrderObject.setPaymentGather(PaymentGatherOB);

		} else {
			PaymentGatherObject.setPurchaseMony(PaymentGatherObject
					.getPurchaseMony()
					+ paymentDetail.getPayMony());
			PaymentGatherObject.setPayPlanMony(PaymentGatherObject
					.getPayPlanMony()
					+ paymentDetail.getPayMony());
			this.getPaymentGatherService().saveOrUpdate(PaymentGatherObject);
			paymentDetail.setPaymentGather(PaymentGatherObject);
			PaymentOrderObject.setPaymentGather(PaymentGatherObject);
		}

		/**
		 * 编码产生
		 */
		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(paymentDetail.getBillCode());
			codes.setCodeMolde("采购票据单");
			codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			this.getCodeService().save(codes);
			paymentDetail.setCode(codes);
			this.getPaymentDetailService().save(paymentDetail);
		} else {
			CodeInvoice Vob = this.getCodeInvoiceService().getVobject(
					codeInvoice.getId());
			Code codes = new Code();
			codes.setCodeValue(paymentDetail.getBillCode());
			codes.setCodeMolde("采购票据单");
			codes.setEntityName(this.getClass().getName());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.getCodeInvoiceService().saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			this.getCodeService().save(codes);
			paymentDetail.setCode(codes);
			this.getPaymentDetailService().save(paymentDetail);
		}

		this.getPaymentOrderService().saveOrUpdate(PaymentOrderObject);
		this.setPrompt("提交成功");
		return SUCCESS;
	}

	@Action("editFundsPayment")
	public String editFundsPayment() {
		payWaylist = this.getPayWayService().getAll();
		bankAccounts = this.getBankAccountService().getAllBankAccount();
		paymentDetail = this.getPaymentDetailService().get(
				paymentDetail.getId());
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@Action(value = "savePurchaseInAccount", results = {
			@Result(name = "success", type = "redirect", location = "listPaymentOrder"),
			@Result(name = "error", type = "chain", location = "editFundsPayment"),
			@Result(name = "none", type = "redirect", location = "listPaymentOrder") })
	public String savePurchaseInAccount() {

		/**
		 * 明细paymentDetail.realityDate paymentDetail.payWay
		 * paymentDetail.bankAccounts
		 */
		if (paymentDetail.getRealityDate() == null) {
			this.addActionError("付款时间不能为空");
			return ERROR;
		}
		if (paymentDetail.getPayWay() == null) {
			this.addActionError("付款方式不能为空");
			return ERROR;
		}
		if (paymentDetail.getBankAccounts() == null) {
			this.addActionError("付款账号不能为空");
			return ERROR;
		}
		try {
			PaymentDetails PaymentDetailObject = this.getPaymentDetailService()
					.get(paymentDetail.getId());
			PaymentDetailObject.setRealityDate(paymentDetail.getRealityDate());
			PaymentDetailObject.setPayWay(paymentDetail.getPayWay());
			PaymentDetailObject.setPayState(2);
			this.getPaymentDetailService().saveOrUpdate(PaymentDetailObject);
			/**
			 * 汇集
			 */

			PaymentGather PaymentGatherObject = this.getPaymentGatherService()
					.getPaymentGatherOb(
							PaymentDetailObject.getPaymentGather().getId());
			if (PaymentGatherObject.getPayRealityMony() == 0
					|| "".equals(PaymentGatherObject.getPayRealityMony())) {
				PaymentGatherObject.setPayRealityMony(paymentDetail
						.getPayMony());
				if (PaymentGatherObject.getPurchaseMony() <= paymentDetail
						.getPayMony()) {
					PaymentGatherObject.setPayState(3);
				}
			} else {
				PaymentGatherObject.setPayRealityMony(PaymentGatherObject
						.getPayRealityMony()
						+ paymentDetail.getPayMony());
				if (PaymentGatherObject.getPurchaseMony() <= (PaymentGatherObject
						.getPayRealityMony() + paymentDetail.getPayMony())) {
					PaymentGatherObject.setPayState(3);
				}
			}
			PaymentGatherObject.setArelityState(2);

			PaymentOrder order = PaymentGatherObject.getPaymentOrder();
			boolean b1 = true;

			for (PaymentDetails details : PaymentGatherObject.getDetails()) {
				if ((details.getBillState() != 2 || details.getPayState() != 2)) {
					b1 = false;
				}
			}
			// System.out.println(order.getPayMony()-PaymentGatherObject.getPayRealityMony()+"  2入账");
			if (b1 == true
					&& (PaymentGatherObject.getPayRealityMony() - PaymentGatherObject
							.getPayPlanMony()) == 0
					&& (order.getPayMony() - PaymentGatherObject
							.getPayRealityMony()) == 0) {
				// System.out.println(2);
				order.setPatState(3);
			}
			this.getPaymentOrderService().saveOrUpdate(order);
			///System.out.println();
			System.out.println(PaymentGatherObject.getPaymentOrder().getId());
			System.out.println(PaymentGatherObject.getPaymentOrder().getPurchaseOrder().getId());
			System.out.println(PaymentGatherObject.getPaymentOrder().getPurchaseOrder().getPayedMoney());
			PaymentGatherObject.getPaymentOrder().getPurchaseOrder()
					.setPayedMoney(
							PaymentGatherObject.getPaymentOrder()
									.getPurchaseOrder().getPayedMoney()
									+ paymentDetail.getPayMony());
			this.getPaymentGatherService().saveOrUpdate(PaymentGatherObject);
			/**
			 * 入账
			 */
			Double sum = this.getDetailService().getBalanceByAccount(
					paymentDetail.getBankAccounts());
			Detail detialob = new Detail();
			detialob.setPaymentDetails(PaymentDetailObject);
			detialob.setPay(paymentDetail.getPayMony());
			detialob.setIncome(0.0);
			detialob.setBalance(sum - paymentDetail.getPayMony());
			detialob.setBankAccount(paymentDetail.getBankAccounts());
			detialob.setItem(Constrains.FS_ITEMS_PURCHASE);
			this.getDetailService().save(detialob);
			this.setPrompt("付款成功");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

	@Action("editVotecounting")
	public String editVotecounting() {
		this.InvoiceTypes = this.getInvoiceTypeService().getAllInvoiceType();
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@Action(value = "savePurchaseBill", results = {
			@Result(name = "success", type = "redirect", location = "listPaymentOrder"),
			@Result(name = "error", type = "chain", location = "editVotecounting"),
			@Result(name = "none", type = "redirect", location = "listPaymentOrder") })
	public String savePurchaseBill() {
		/**
		 * 开票金额
		 */
		if (votecounting.getVotecountDate() == null) {
			this.addActionError("开票时间不能太为空");
			return ERROR;
		}
		if (votecounting.getInvoiceType() == null) {
			this.addActionError("开票类型不能为空");
			return ERROR;
		}
		if (votecounting.getBillCode() == null
				|| votecounting.getBillCode().equals("")) {
			this.addActionError("票据单号不能为空");
			return ERROR;
		}
		this.getVotecountingService().save(votecounting);
		PaymentDetails PaymentDetailsObject = this.getPaymentDetailService()
				.getPaymentDetail(paymentDetail.getId());
		PaymentDetailsObject.setBillState(2);
		PaymentDetailsObject.setVotecounting(votecounting);
		this.getPaymentDetailService().saveOrUpdate(PaymentDetailsObject);

		PaymentGather PaymentGatherObject = this.getPaymentGatherService()
				.getPaymentGatherOb(paymentGather.getId());
		if (PaymentGatherObject.getBillMony() == 0
				|| "".equals(PaymentGatherObject.getBillMony())) {
			PaymentGatherObject.setBillMony(PaymentDetailsObject.getPayMony());
		} else {
			PaymentGatherObject.setBillMony(PaymentGatherObject.getBillMony()
					+ PaymentDetailsObject.getPayMony());
		}
		if (PaymentGatherObject.getPayPlanMony()
				- PaymentGatherObject.getBillMony() <= 0) {
			PaymentGatherObject.setBillState(3);
		} else {
			PaymentGatherObject.setBillState(2);
		}
		PaymentOrder order = PaymentGatherObject.getPaymentOrder();
		boolean b1 = true;

		for (PaymentDetails details : PaymentGatherObject.getDetails()) {
			if (details.getBillState() != 2 || details.getPayState() != 2) {
				b1 = false;
			}
		}
		// System.out.println(order.getPayMony()-PaymentGatherObject.getPayRealityMony()+"  1发票");
		if (b1 == true
				&& (PaymentGatherObject.getPayRealityMony() - PaymentGatherObject
						.getPayPlanMony()) == 0
				&& (order.getPayMony() - PaymentGatherObject
						.getPayRealityMony()) == 0) {
			// System.out.println(1);
			order.setPatState(3);
		}
		this.getPaymentOrderService().saveOrUpdate(order);
		this.getPaymentGatherService().saveOrUpdate(PaymentGatherObject);
		this.setPrompt("开票成功");
		return SUCCESS;
	}

	@Action("listPayment")
	public String excute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				PaymentGather.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getPaymentOrderService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	public PaymentOrder getPaymentOrder() {
		return paymentOrder;
	}

	public void setPaymentOrder(PaymentOrder paymentOrder) {
		this.paymentOrder = paymentOrder;
	}

	public PaymentDetails getPaymentDetail() {
		return paymentDetail;
	}

	public void setPaymentDetail(PaymentDetails paymentDetail) {
		this.paymentDetail = paymentDetail;
	}

	public PaymentGather getPaymentGather() {
		return paymentGather;
	}

	public void setPaymentGather(PaymentGather paymentGather) {
		this.paymentGather = paymentGather;
	}

	public PaymentDetailService getPaymentDetailService() {
		return paymentDetailService;
	}

	public void setPaymentDetailService(
			PaymentDetailService paymentDetailService) {
		this.paymentDetailService = paymentDetailService;
	}

	public PaymentOrderService getPaymentOrderService() {
		return paymentOrderService;
	}

	public void setPaymentOrderService(PaymentOrderService paymentOrderService) {
		this.paymentOrderService = paymentOrderService;
	}

	public PaymentGatherService getPaymentGatherService() {
		return paymentGatherService;
	}

	public void setPaymentGatherService(
			PaymentGatherService paymentGatherService) {
		this.paymentGatherService = paymentGatherService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public PurchaseOrder getPurchaseOrder() {
		return purchaseOrder;
	}

	public void setPurchaseOrder(PurchaseOrder purchaseOrder) {
		this.purchaseOrder = purchaseOrder;
	}

	public PurchaseOrderService getPurchaseOrderService() {
		return purchaseOrderService;
	}

	public void setPurchaseOrderService(
			PurchaseOrderService purchaseOrderService) {
		this.purchaseOrderService = purchaseOrderService;
	}

	public PayWay getPayWay() {
		return payWay;
	}

	public void setPayWay(PayWay payWay) {
		this.payWay = payWay;
	}

	public PayWayService getPayWayService() {
		return payWayService;
	}

	public void setPayWayService(PayWayService payWayService) {
		this.payWayService = payWayService;
	}

	public List<PayWay> getPayWaylist() {
		return payWaylist;
	}

	public void setPayWaylist(List<PayWay> payWaylist) {
		this.payWaylist = payWaylist;
	}

	public BankAccount getBankAccount() {
		return bankAccount;
	}

	public void setBankAccount(BankAccount bankAccount) {
		this.bankAccount = bankAccount;
	}

	public BankAccountService getBankAccountService() {
		return bankAccountService;
	}

	public void setBankAccountService(BankAccountService bankAccountService) {
		this.bankAccountService = bankAccountService;
	}

	public Collection<BankAccount> getBankAccounts() {
		return bankAccounts;
	}

	public void setBankAccounts(Collection<BankAccount> bankAccounts) {
		this.bankAccounts = bankAccounts;
	}

	public DetailService getDetailService() {
		return detailService;
	}

	public void setDetailService(DetailService detailService) {
		this.detailService = detailService;
	}

	public StoreRoomService getStoreRoomService() {
		return storeRoomService;
	}

	public void setStoreRoomService(StoreRoomService storeRoomService) {
		this.storeRoomService = storeRoomService;
	}

	public List<StoreRoom> getStorerooms() {
		return storerooms;
	}

	public void setStorerooms(List<StoreRoom> storerooms) {
		this.storerooms = storerooms;
	}

	public Votecounting getVotecounting() {
		return votecounting;
	}

	public void setVotecounting(Votecounting votecounting) {
		this.votecounting = votecounting;
	}

	public VotecountingService getVotecountingService() {
		return votecountingService;
	}

	public void setVotecountingService(VotecountingService votecountingService) {
		this.votecountingService = votecountingService;
	}

	public List<Votecounting> getVotecountings() {
		return votecountings;
	}

	public void setVotecountings(List<Votecounting> votecountings) {
		this.votecountings = votecountings;
	}

	public InvoiceTypeService getInvoiceTypeService() {
		return invoiceTypeService;
	}

	public void setInvoiceTypeService(InvoiceTypeService invoiceTypeService) {
		this.invoiceTypeService = invoiceTypeService;
	}

	public List<InvoiceType> getInvoiceTypes() {
		return InvoiceTypes;
	}

	public void setInvoiceTypes(List<InvoiceType> invoiceTypes) {
		InvoiceTypes = invoiceTypes;
	}

	public String getPayMony() {
		return payMony;
	}

	public void setPayMony(String payMony) {
		this.payMony = payMony;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public CodeInvoice getCodeInvoice() {
		return codeInvoice;
	}

	public void setCodeInvoice(CodeInvoice codeInvoice) {
		this.codeInvoice = codeInvoice;
	}

	public CodeInvoiceService getCodeInvoiceService() {
		return codeInvoiceService;
	}

	public void setCodeInvoiceService(CodeInvoiceService codeInvoiceService) {
		this.codeInvoiceService = codeInvoiceService;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeInvoice> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeInvoice> codelist) {
		this.codelist = codelist;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}
}
